from rest_framework import serializers
from api import models
from django.forms import model_to_dict


class CommentModelSerializer(serializers.ModelSerializer):
    create_date = serializers.DateTimeField(format="%Y-%d-%m %H:%M")
    user__nickname = serializers.CharField(source='user.nickname')
    user__avatar = serializers.CharField(source='user.avatar')
    reply_id = serializers.CharField(source='reply.id')
    reply__user__nickname = serializers.CharField(source='reply.user.nickname')
    favor = serializers.SerializerMethodField()

    class Meta:
        model = models.CommentRecord
        # fields = "__all__"
        exclude = ['news', 'user', 'reply', 'root', 'favor_count']

    def get_favor(self, obj):
        user_object = self.context['request'].user
        if not user_object:
            return False
        # 判断是否有赞
        exists = models.CommentFavorRecord.objects.filter(comment=obj, user=user_object).exists()
        return exists


class CreateCommentModelSerializer(serializers.ModelSerializer):
    # read_only是用户提交不用添加该数据
    create_date = serializers.DateTimeField(format="%Y-%d-%m %H:%M", read_only=True)
    user__nickname = serializers.CharField(source='user.nickname', read_only=True)
    user__avatar = serializers.CharField(source='user.avatar', read_only=True)
    reply_id = serializers.CharField(source='reply.id', read_only=True)
    reply__user__nickname = serializers.CharField(source='reply.user.nickname', read_only=True)

    class Meta:
        model = models.CommentRecord
        # fields = "__all__"
        exclude = ['user', 'favor_count']
